package com.xuecheng.govern.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@Component
public class MyFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
//        返回true表示执行此过滤器
        return true;
    }

    @Override
    public Object run() throws ZuulException {
//        获取request对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
//        获取请求头
        String header = request.getHeader("Authorization");
        if (StringUtils.isEmpty(header)) {
            return null;

        } else {
            HttpServletResponse response = requestContext.getResponse();
            response.setContentType("application/json;charset=utf-8");
//            设置响应信息
            ResponseResult responseResult = new ResponseResult(CommonCode.SUCCESS);
            String jsonString = JSON.toJSONString(responseResult);
            requestContext.setResponseBody(jsonString);
            response.setStatus(200);
            return null;
        }
    }
}
